package com.digitalchina.lxnsy.activity.old;

import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.MainV4FragmentAdapter;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.fragment.Main1Fragment;
import com.digitalchina.lxnsy.sy.main.Main2Fragment;
import com.digitalchina.lxnsy.sy.main.Main3Fragment;
import com.digitalchina.lxnsy.sy.main.Main4Fragment;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.view.NoScrollViewPager;
import com.digitalchina.lxnsy.xml.RongCloudXML;
import com.digitalchina.lxnsy.xml.UserXML;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/1/9 17:28
 * 修改备注：
 * ================================================
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private final int MODULE_NUMBER = 4;
    private final int INDEX_0 = 0;
    private final int INDEX_1 = 1;
    private final int INDEX_2 = 2;
    private final int INDEX_3 = 3;

    //用户apk更新用户取消后24小时再次提醒用户更新
    public static final long ONE_DAY_MILLIS = 24 * 60 * 60 * 1000; // 一天的时间  毫秒数表示

   // private MainHomePageV3Fragment f1;
    private Main1Fragment f1;

    private Main2Fragment f4;
    private Main3Fragment f2;
    private Main4Fragment f3;

    private MainV4FragmentAdapter mAdapter;
    private ArrayList<Fragment> mFragmentList;
    private NoScrollViewPager viewPager;
    private int miCurrentIndex;
    private LinearLayout[] maLayouts = new LinearLayout[MODULE_NUMBER];
    private TextView[] mAtv = new TextView[MODULE_NUMBER];
    private ImageView[] mAiv = new ImageView[MODULE_NUMBER];

    private LinearLayout LayoutMsg;
    private LinearLayout LayoutBzh;


    // 未选中的图标
    private int[] drawable = {R.drawable.ic_fg_main_home_unselected, R.drawable.ic_fg_main_deal, R.drawable.ic_fg_main_msg_unselected, R.drawable.ic_fg_main_mine_unselect};
    // 选中的图标
    private int[] drawableCheck = {R.drawable.ic_fg_main_home_selected, R.drawable.ic_fg_main_deal_ture, R.drawable.ic_fg_main_msg_selected, R.drawable.ic_fg_main_mine_selected};

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_main);
        hideActionBar();
    }

    @Override
    public void initMember() {

        if (StringUtil.isStrEmpty(UserXML.getAgreement(activity))) {
            new MaterialDialog.Builder(activity)
                    .title("农科专家使用协议")
                    .content("农科专家重视您的个人隐私信息保护。为确保您的个人权益不受侵害，在使用农科专家功能,请务必仔细阅读并充分理解相关协议。如您同意所有条款，请点击“同意”按钮，开始使用农科专家服务!")
//                    .neutralText("《使用协议》")
                    .positiveText("同意")
                    .negativeText("拒绝")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            UserXML.setAgreement(activity);
                            dialog.dismiss();
                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            ActivityTaskManager.getInstance().closeAllActivity();
                        }
                    })
                    .onNeutral(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            Map<String, String> map = new HashMap<>();
                            map.put("url", URL.URL_GET_PROTOCOL_INFO + "?type=1");
                            map.put("title", "使用协议");
                            GotoUtil.gotoActivity(activity, WebViewActivity.class, "map", map);
                        }
                    })
                    .autoDismiss(false)
                    .cancelable(false)
                    .show();
        }

        mFragmentList = new ArrayList<>();
        viewPager = (NoScrollViewPager) findViewById(R.id.main_viewpager);


        LayoutMsg = (LinearLayout) findViewById(R.id.main_ll_message);
        LayoutBzh = (LinearLayout) findViewById(R.id.main_ll_deal);

        if (UserXML.getLoginStatus(getApplication()).equals(UserXML.USER_IS_LOGIN_VALUE)) {
            if ("null".equals(RongCloudXML.getSubjectenterprisetype(getApplication(), "subjectEnterpriseType"))) {
                LayoutBzh.setVisibility(View.GONE);
            } else {
                LayoutBzh.setVisibility(View.VISIBLE);

            }
        } else {
            LayoutBzh.setVisibility(View.GONE);
        }
        maLayouts[INDEX_0] = (LinearLayout) findViewById(R.id.main_ll_expert);
        maLayouts[INDEX_1] = LayoutBzh;
        maLayouts[INDEX_2] = LayoutMsg;
        maLayouts[INDEX_3] = (LinearLayout) findViewById(R.id.main_ll_my);

        mAtv[INDEX_0] = (TextView) findViewById(R.id.main_tv_expert);
        mAtv[INDEX_1] = (TextView) findViewById(R.id.main_tv_deal);
        mAtv[INDEX_2] = (TextView) findViewById(R.id.main_tv_message);
        mAtv[INDEX_3] = (TextView) findViewById(R.id.main_tv_my);

        mAiv[INDEX_0] = (ImageView) findViewById(R.id.main_iv_expert);
        mAiv[INDEX_1] = (ImageView) findViewById(R.id.main_iv_deal);
        mAiv[INDEX_2] = (ImageView) findViewById(R.id.main_iv_message);
        mAiv[INDEX_3] = (ImageView) findViewById(R.id.main_iv_my);

      //  f1 = new MainHomePageV3Fragment();
        f1 = new Main1Fragment();

        f4 = new Main2Fragment();
        f2 = new Main3Fragment();
        f3 = new Main4Fragment();

        mFragmentList.add(f1);
        mFragmentList.add(f4);
        mFragmentList.add(f2);
        mFragmentList.add(f3);


        mAdapter = new MainV4FragmentAdapter(getSupportFragmentManager(), mFragmentList);
        viewPager.setAdapter(mAdapter);

        viewPager.setOffscreenPageLimit(MODULE_NUMBER);

        miCurrentIndex = INDEX_0;
        updateColor();

    }


    /**
     * 点击底部导航改变当前按钮状态
     */
    private void updateColor() {
        for (int i = 0; i < mAtv.length; i++) {
            if (miCurrentIndex == i) {
                setColor(mAtv[i], getResources().getColor(R.color.app_color));
                setIco(mAiv[i], drawableCheck[i]);
            } else {
                setColor(mAtv[i], getResources().getColor(R.color.colorFontGray));
                setIco(mAiv[i], drawable[i]);
            }
        }
    }

    /**
     * 设置文字颜色
     *
     * @param pTv
     * @param piColor
     */
    private void setColor(TextView pTv, int piColor) {
        pTv.setTextColor(piColor);
    }

    /**
     * 设置图标颜色
     *
     * @param pIv
     * @param index
     */
    private void setIco(ImageView pIv, int index) {
        pIv.setBackgroundResource(index);
    }


    @Override
    public void addListener() {

        for (LinearLayout moLayout : maLayouts) {
            moLayout.setOnClickListener(this);
        }

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                miCurrentIndex = position;
                updateColor();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                }
            }
        };
    }


    @Override
    public void callBack(Object object) {
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.main_ll_expert:
                miCurrentIndex = INDEX_0;
                break;
            case R.id.main_ll_deal:
                miCurrentIndex = INDEX_1;
                break;
            case R.id.main_ll_message:
                if (!Utils.isLogin(MainActivity.this)) {
                    Utils.notLoginGoto(MainActivity.this);
                    return;
                }
                miCurrentIndex = INDEX_2;
                break;
            case R.id.main_ll_my:
                miCurrentIndex = INDEX_3;
                break;
        }
        viewPager.setCurrentItem(miCurrentIndex, false);
        updateColor();

    }

    @Override
    protected void onResume() {
        super.onResume();


        // 检查APK更新
      //  if ("default".equals(UpdateCancelXML.getCancelTime(this)) || System.currentTimeMillis() - Long.parseLong(UpdateCancelXML.getCancelTime(this)) >= ONE_DAY_MILLIS) // 没有取消过更新
         //   UpdateApk.update();
    }

    /**
     * 获取token成功 保存用户信息并跳转
     */
    private void getTokenSuccess(Object obj) {

        LogUtils.e("获取服务端Token成功,已保存到XML");

        // 解析获取到的token
        String token = FastJsonUtil.getString(obj.toString(), "data");
        RongCloudXML.setUserToken(MainActivity.this, UserXML.getUserId(this), token);

    }
}
